﻿using Api.Core.Auth;
using Api.Core.Common.Auth;
using Api.Core.Common.Cache;
using Api.Core.Common.Helper;
using Api.Core.IServices.User;
using Api.Core.Model.User;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Api.Core.Controllers
{

    public class LoginController : BaseController
    {
        private readonly IAuthServer _authServer;
        private readonly IUserInfoService _userInfo;
        private readonly IRedisCache _cache;
        private readonly AuthSetting _authSetting;

        public LoginController(
            IAuthServer authServer
            , IUserInfoService userInfo,
            IRedisCache cache,
            IOptions<AuthSetting> authSetting)
        {
            _authServer = authServer;
            _userInfo = userInfo;
            _cache = cache;
            _authSetting = authSetting.Value;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userCredentials"></param>
        /// <returns></returns>
        [HttpPost("login")]

        [AllowAnonymous]
        public virtual async Task<IActionResult> LoginAsync(UserCredentials userCredentials)
        { 
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            userCredentials.Password = MD5Helper.MD5Encrypt32(userCredentials.Password);

            var userInfo =await _userInfo.Query(x => x.UserName == userCredentials.UserName && x.Password == userCredentials.Password);
            //userInfo.Add(new UserEntity { UserId = "test11", UserName = "test11", IsDel = false, Password = "test11" });
            if (userInfo.Count > 0)
            {
                var userModel = userInfo.FirstOrDefault();

                var cacheToken = _cache.GetValue(userModel.UserId);
                if (!string.IsNullOrWhiteSpace(cacheToken))
                {
                    _cache.Remove(userModel.UserId);
                    /*var Result = new AuthResult()
                    {
                        success = true,
                        token = cacheToken.Replace("\"", ""),
                        message = "请勿重复请求Token，返回当前有效Token！"
                    };
                    return Ok(Result);*/
                }
                var response = await _authServer.CreateAuthentication(userModel);
                if (!response.success)
                {
                    return BadRequest(response.message);
                }
                _cache.Set(userModel.UserId, response.token, _authSetting.TokenLifetime * 2);
                return Ok(response);
            }
            else
            {
                return new JsonResult(new
                {
                    success = false,
                    message = "认证失败"
                });
            }
        }

        [HttpGet("RefreshToken")]
        [AllowAnonymous]
        public async Task<IActionResult> RefreshToken(RefreshCredentials refreshCredentials)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var JwtModel = _authServer.SerializeJwt(refreshCredentials.OldToken);
            if (JwtModel == null)
            {
                return new JsonResult(new
                {
                    success = false,
                    message = "token无效，请重新登录！"
                });
            }
            var userInfo = await _userInfo.Query(x => x.UserId == JwtModel.UserId);

            if (userInfo != null)
            {
                var userModel = userInfo.FirstOrDefault();

                var cacheToken = _cache.GetValue(userModel.UserId);
                if (string.IsNullOrWhiteSpace(cacheToken))
                {
                    return new JsonResult(new
                    {
                        success = false,
                        message = "token已过期，请重新登录！"
                    });
                }

                var response = await _authServer.CreateAuthentication(userInfo.FirstOrDefault());
                if (!response.success)
                {
                    return BadRequest(response.message);
                }
                _cache.Set(userModel.UserId, response.token, _authSetting.TokenLifetime * 2);

                return Ok(response);
            }
            else
            {
                return new JsonResult(new
                {
                    success = false,
                    message = "认证失败"
                });
            }
        }

        /// <summary>
        /// token强制失效
        /// </summary>
        /// <param name="refreshCredentials"></param>
        /// <returns></returns>
        [HttpPost("Mandatoryoffline")]
        [Authorize(Roles = "超级管理员")]
        public IActionResult Mandatoryoffline(RefreshCredentials refreshCredentials)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            var JwtModel = _authServer.SerializeJwt(refreshCredentials.OldToken);
            if (JwtModel != null)
            {
                _cache.Remove(JwtModel.UserId);
            }
            return new JsonResult(new
            {
                success = true,
                message = "token强制失效成功！"
            });
        }

    }
}